import json
import time

from django.http import HttpResponse
# 导入websocket装饰器
from dwebsocket.decorators import accept_websocket

ws_list = []  # websocket 客户端列表, 所有和服务器建立连接的页面
ws_set = set()  # 使用set保存客户端

@accept_websocket
def echo(request):
    ws = request.websocket
    # for msg in ws:
    #     ws.send(msg)
    ws_set.add(ws)
    for msg in ws:
        for ws in ws_set:
            ws.send(msg)
    # ws.send('open ws')  # 发送消息到客户端
    # while 1:
    #     print('while')
    #     # time.sleep(1)
    #     # msg = ws.read()  # 非阻塞
    #     msg = ws.wait()
    #     if msg:
    #         for ws in ws_list:
    #             ws.send(msg)


# 主动推送消息
def pushws(request):
    msg = request.GET.get('msg')
    if msg:
        for ws in ws_list:
            ws.send(msg)

    return HttpResponse('消息发送成功')
